//
//  UserTagsViewController.m
//  Molian
//
//  Created by 胡津 on 15/4/2.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#define LINE_HEIGHT 30//行距

#import "UserTagsViewController.h"
#import "WWTagsCloudView.h"
#import "DWTagList.h"
#define kTopHeigth 80
@interface UserTagsViewController ()<WWTagsCloudViewDelegate>
@property (strong, nonatomic) WWTagsCloudView* tagCloud;
@property (strong, nonatomic) UIView *cellview;
@end

@implementation UserTagsViewController
{
    DWTagList *tagList;
    UITextField *tagTextField;
    UITextField *priceTextField;
}

@synthesize Delegate;


- (void)tapView
{
    if (tagTextField) {
       [tagTextField resignFirstResponder];
    }
    if (priceTextField) {
        [priceTextField resignFirstResponder];
    }
}
- (void)setTopView
{
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, kTopHeigth)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 20)];
    label.textColor = RGBA(122, 122, 122, 1);
    label.font = kFont(12);
    label.backgroundColor  = APPCOLORBACKGROUNDCOLOR(1);
    label.text = @"  输入你希望的价格";
    [topView addSubview:label];
    
    priceTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 20, DeviceWidth - 120, 40)];
    priceTextField.textColor = RGBA(122, 122, 122, 1);
    priceTextField.font = kFont(12);
    priceTextField.keyboardType = UIKeyboardTypeNumberPad;
    if (self.price) {
        priceTextField.text = [NSString stringWithFormat:@"%.2f",self.price];
    }
    [topView addSubview:priceTextField];
    
    
    UILabel *hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(DeviceWidth - 100, 20, 100, 40)];
    hintLabel.text = @"(单位:元/小时)";
    hintLabel.font = kFont(12);
    hintLabel.textColor = RGBA(122, 122, 122, 1);
    [topView addSubview:hintLabel];
    
    
    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, kTopHeigth-20, DeviceWidth, 20)];
    label2.textColor = RGBA(122, 122, 122, 1);
    label2.font = kFont(12);
    label2.backgroundColor  = APPCOLORBACKGROUNDCOLOR(1);
    label2.text = @"  选择或输入标签";
    [topView addSubview:label2];
    
}
- (BOOL)checkNum:(NSString *)str
{
    NSString *regex =@"^[0-9]+([.]{0,1}[0-9]+){0,1}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    if (!isMatch) {
        [HUD Prompt:@"价格只能输入大于0的数字"];
        return NO;
    }
    return YES;
}
- (void)clickLeftBt
{
    //是约会
    if (self.isDate) {
        NSArray *arr = [tagList textArray];
        NSString *str = priceTextField.text;
        if ((arr&&arr.count)||(str&&str.length)) {
            //有一个存在,则必须都存在
            if((arr&&arr.count)&&(str&&str.length)){
                
                if (![self checkNum:str]) {
                    return;
                }
                
                CGFloat price = [str floatValue];
                if ([Delegate respondsToSelector:@selector(datePrice:Tags:)]) {
                    [Delegate datePrice:price Tags:arr];
                }
                
            }else{
                HUD * hud = [[HUD alloc]init];
                [hud HUDImage:nil Title:@"价格和约会内容必须同时存在" Content:@"不保存退出?" CANCEL:@"是的" Confirm:@"取消"];
                hud.Cancel = ^{
                    [self.navigationController popViewControllerAnimated:YES];
                };
                hud.Confirm = ^{
                    
                };
                [self.view addSubview:hud];
                return;
            }
        }
        
    }
    [self.navigationController popViewControllerAnimated:YES];
    [self.view removeFromSuperview];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView)];
    [self.view addGestureRecognizer:tapGR];
    
    
   // self.title = @"我喜欢的";
    [AVAnalytics event:@"我喜欢的页面访问"]; // 通知服务器一个点击事件。

    self.edgesForExtendedLayout = UIRectEdgeNone;
    CGFloat h = 20;
    if (self.isDate) {
        UIButton *leftBt = [UIButton buttonWithType:UIButtonTypeCustom];
        [leftBt sizeToFit];
        [leftBt setTitle:@"返回" forState:UIControlStateNormal];
        [leftBt setContentMode:UIViewContentModeCenter];
        [leftBt setImage:[UIImage imageNamed:@"back_normal"] forState:UIControlStateNormal];
        [leftBt setImageEdgeInsets:UIEdgeInsetsMake(-2,-18, -2, 0)];
        [leftBt setTitleEdgeInsets:UIEdgeInsetsMake(0, -12, 0, -10)];
        leftBt.titleLabel.font = kFont(17);
        leftBt.frame = CGRectMake(0, 0, 40, 30);
        leftBt.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [leftBt addTarget:self action:@selector(clickLeftBt) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBarBt = [[UIBarButtonItem alloc] initWithCustomView:leftBt];
        self.navigationItem.leftBarButtonItems = @[leftBarBt];
        //屏幕边缘手势
        UIScreenEdgePanGestureRecognizer *screenEdgePanGR = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(clickLeftBt)];
        screenEdgePanGR.edges  = UIRectEdgeLeft;
        [self.view addGestureRecognizer:screenEdgePanGR];
        
        
        
        
        h = 20+kTopHeigth;
        [self setTopView];
    }
    
    self.cellview = [[UIView alloc]initWithFrame:CGRectMake(-1, h, DeviceWidth+1, 150)];
    self.cellview.backgroundColor = [UIColor whiteColor];
    [self.cellview.layer setBorderColor:[[UIColor blackColor] colorWithAlphaComponent:0.2].CGColor];
    [self.cellview.layer setBorderWidth:0.5];
    [self.view addSubview:self.cellview];
    
    //标签数据
//    _tags = @[@"当幸福来敲门", @"海滩", @"如此的夜晚", @"大进军", @"险地", @"姻缘订三生", @"死亡城", @"苦海孤雏", @"老人与海", @"烽火异乡情", @"父亲离家时", @"无情大地补情天", @"以眼还眼", @"锦绣人生", @"修女传", @"第十三号", @"末代启示录", @"西北前线", @"西北区骑警", @"黄金广场大劫案", @"畸恋山庄", @"守夜", @"我们爱黑夜", @"恐怖夜校", @"夏尔洛结婚", @"特别的一夜", @"下一站格林威治村", @"升职记", @"恶夜之吻", @"木匠兄妹故事", ];
    
    NSArray* colors = @[RGBA(128, 128, 176, 1), RGBA(188, 120, 162, 1), RGBA(132, 181, 141, 1), RGBA(147, 176, 211, 1)];
    NSArray* fonts = @[[UIFont fontWithName:FontName size:13], [UIFont fontWithName:FontName size:14],[UIFont fontWithName:FontName size:16]];
    //初始化选择标签
    _tagCloud = [[WWTagsCloudView alloc] initWithFrame:CGRectMake(0, 200+h-20, DeviceWidth, 200)
                                               andTags:_tags
                                          andTagColors:colors
                                              andFonts:fonts
                                       andParallaxRate:1.7
                                          andNumOfLine:3];
    _tagCloud.delegate = self;
    [self.view addSubview:_tagCloud];

    
    //初始化选中标签
    tagList = [[DWTagList alloc] initWithFrame:CGRectMake(0, 10, DeviceWidth, 120)];
    [self.cellview addSubview:tagList];
    if(!self.noImport){
        //手动输入
        tagTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, self.cellview.frame.size.height-45, DeviceWidth-120, 35)];
        tagTextField.placeholder = @"手动输入标签";
        tagTextField.layer.masksToBounds = YES;//开启圆角
        [tagTextField.layer setCornerRadius:CGRectGetHeight([tagTextField bounds]) / 2];
        [tagTextField.layer setBorderColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.5].CGColor];
        [tagTextField.layer setBorderWidth:1];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
        tagTextField.leftView = view;//缩进
        tagTextField.leftViewMode  = UITextFieldViewModeAlways;
        [self.cellview addSubview:tagTextField];
        
        //添加按钮
        BFPaperButton *addBtn = [[BFPaperButton alloc]init];
        addBtn.frame = CGRectMake(DeviceWidth-80, self.cellview.frame.size.height-45, 70, 35);
        [addBtn setBackgroundColor:APPCOLOR(1)];
        [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        addBtn.tapCircleColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        addBtn.layer.masksToBounds = YES;//开启圆角
        [addBtn.layer setCornerRadius:CGRectGetHeight([addBtn bounds]) / 2];
        addBtn.titleLabel.font = [UIFont fontWithName:FontName size:15];
        [addBtn setTitle:@"添加" forState:UIControlStateNormal];
        [addBtn addTarget:self action:@selector(addTag) forControlEvents:UIControlEventTouchUpInside];
        [addBtn setTintColor:[UIColor blackColor]];
        [self.cellview addSubview:addBtn];
    }
    
    if (!self.maxTextCount) {
        self.maxTextCount = 6;
    }
    
    if (!self.maxCount) {
        self.maxTextCount = 8;
    }
    //提示文字
    UILabel *placeholderLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, self.cellview.frame.size.height+10+h-20, DeviceWidth-40, 40)];
    placeholderLabel.text =   [NSString stringWithFormat:@"最多可以添加%ld个标签,每个标签最多%ld个字",self.maxCount,(long)self.maxTextCount];
    placeholderLabel.font = [UIFont fontWithName:FontName size:14];
    placeholderLabel.textColor = [UIColor lightGrayColor];
    [self.view addSubview:placeholderLabel];
    
    //添加按钮
    BFPaperButton *random = [[BFPaperButton alloc]init];
    random.frame = CGRectMake((DeviceWidth-120)/2, 400-30+h-20, 120, 40);
    [random setBackgroundColor:APPCOLOR(1)];
    [random setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    random.tapCircleColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
    random.layer.masksToBounds = YES;//开启圆角
    [random.layer setCornerRadius:CGRectGetHeight([random bounds]) / 2];
    random.titleLabel.font = [UIFont fontWithName:FontName size:15];
    [random setTitle:@" 换一批" forState:UIControlStateNormal];
    [random setImage:[UIImage imageNamed:@"me_refresh_icon"] forState:UIControlStateNormal];
    [random addTarget:self action:@selector(random) forControlEvents:UIControlEventTouchUpInside];
    [random setTintColor:[UIColor blackColor]];
    [self.view addSubview:random];
    
   
}
- (void)setprice:(CGFloat)price
{
    if (price&&priceTextField) {
        priceTextField.text = [NSString stringWithFormat:@"%.2f",price];
    }
}
-(void)random
{
    [_tagCloud reloadAllTags];
}

-(void)nowTagsAr:(NSArray *)tagsArr
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [tagList.textArray addObjectsFromArray:tagsArr];
        [tagList setTags:[tagList textArray]];
    });
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    if (!self.isDate&&[Delegate respondsToSelector:@selector(UserTags:)]) {
        [Delegate UserTags:[tagList textArray]];
    }
}

-(void)addTag
{
    if (tagTextField.text.length < 2 ) {
        NSString *str = [NSString stringWithFormat:@"标签需 2-%ld 个字",(long)self.maxTextCount];
        [HUD Prompt:str];
        
        return;
    }
    if ( tagTextField.text.length >=self.maxTextCount) {
        NSString *str = [NSString stringWithFormat:@"标签需 2-%ld 个字",(long)self.maxTextCount];
        [HUD Prompt:str];
        return;
    }
    
    [self addTagStr:tagTextField.text];
}


-(void)tagClickAtIndex:(NSInteger)tagIndex
{
    
    [self addTagStr:_tags[tagIndex]];

}

-(void)addTagStr:(NSString*)Tagstr
{
    for (NSString * str in [tagList textArray])
    {
        if ([str isEqualToString:Tagstr]){
            [HUD Prompt:@"已经添加过了"];
            return;
            break;//一定要有break，否则会出错的。
        }
    }
    
    if ([tagList textArray].count  >= self.maxCount) {
         NSString *str = [NSString stringWithFormat:@"最多可以添加%ld个",(long)self.maxCount];
        [HUD Prompt:str];
        return;
    }
    tagTextField.text = @"";
    if (self.maxCount == 1) {
        //文字很多,只需要添加一个标签就行
        [[tagList textArray] removeAllObjects];
    }
    [[tagList textArray] addObject:Tagstr];
    [tagList setTags:[tagList textArray]];
    
}


//根据label的字体和文字内容获取label宽度
-(CGFloat)getLabelWidthWithLabel:(UILabel*)label
{
    NSDictionary *attribute = @{NSFontAttributeName: label.font};
    CGSize retSize = [label.text boundingRectWithSize:CGSizeMake(MAXFLOAT, label.font.lineHeight)
                                              options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute
                                              context:nil].size;
    return retSize.width;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}


@end
